package org.goyo.main.services.system.impl;

import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.goyo.common.exception.DBException;
import org.goyo.common.exception.ServiceException;
import org.goyo.common.utils.Pager;
import org.goyo.common.utils.ToolUtils;
import org.goyo.main.domain.dao.system.ISysUserDao;
import org.goyo.main.domain.dao.system.ISysUserDepGroupDao;
import org.goyo.main.domain.dao.system.ISysUserMenuDao;
import org.goyo.main.domain.dao.system.ISysUserRoleDao;
import org.goyo.main.domain.entity.base.Customer;
import org.goyo.main.domain.entity.system.SysDepGroup;
import org.goyo.main.domain.entity.system.SysRole;
import org.goyo.main.domain.entity.system.SysUser;
import org.goyo.main.domain.entity.system.SysUserDepGroup;
import org.goyo.main.domain.entity.system.SysUserMenu;
import org.goyo.main.domain.entity.system.SysUserRole;
import org.goyo.main.domain.excelBean.CustomerExcel;
import org.goyo.main.domain.excelBean.SysUserExcel;
import org.goyo.main.services.system.ISysUserService;
import org.goyo.main.web.controller.system.SessionUtil;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class SysUserServiceImpl implements ISysUserService{

	@Resource
	private ISysUserDao sysUserDao;
	@Resource
	private ISysUserRoleDao sysUserRoleDao;
	@Resource
	private ISysUserDepGroupDao sysUserDepGroupDao;
	@Resource
	private ISysUserMenuDao sysUserMenuDao;
	@Resource
	private PasswordEncoder passwordEncoder;
	
	@Override
	public SysUser saveOrUpdateInfo(SysUser info,List<SysRole> sysRoles,String groupIds,String menuIds) throws DBException, ServiceException{
		String uuid = null;
		//保存用户数据
		//新建用户密码为123456
		if(info.getUuid() == null || "".equals(info.getUuid())){
			info.setUuid(null);
			String password = passwordEncoder.encodePassword("123456", null);
			info.setPassword(password);
			uuid = sysUserDao.save(info);
		}else{
			sysUserDao.update(info);
			uuid = info.getUuid();
		}
		sysUserDao.flush();
		Set<String> roleIdSet = ToolUtils.getFiles(sysRoles,"uuid");
		
		//删除角色权限相关数据
		sysUserRoleDao.delBatch(SysUserRole.class, "userId", new Object[]{uuid});
		sysUserDao.flush();
		if(roleIdSet != null){
			for(String roleId : roleIdSet){
				SysUserRole userRole = new SysUserRole();
				userRole.setRoleId(roleId);
				userRole.setUserId(uuid);
				sysUserRoleDao.save(userRole);
			}
		}
		//删除用户组织相关数据
		sysUserDepGroupDao.delBatch(SysUserDepGroup.class, "userId",new Object[]{uuid});
		sysUserDao.flush();

		//保存用户组织数据
		if(groupIds != null && !"".equals(groupIds)){
			String[] ids  = groupIds.split(",");
			for(String  groupId : ids){
				SysUserDepGroup userGroup = new SysUserDepGroup();
				userGroup.setUserId(uuid);
				userGroup.setDepGroupId(groupId);
				sysUserDepGroupDao.save(userGroup);
			}
		}
		
		//删除用户菜单关数据
		sysUserMenuDao.delBatch(SysUserMenu.class, "userId",new Object[]{uuid});
		sysUserDao.flush();

		//保存用户菜单数据
		if(menuIds != null && !"".equals(menuIds)){
			String[] ids  = menuIds.split(",");
			for(String  menuId : ids){
				SysUserMenu userMenu = new SysUserMenu();
				userMenu.setUserId(uuid);
				userMenu.setMenuId(menuId);
				sysUserMenuDao.save(userMenu);
			}
		}
		
		return info;
	}

	@Override
	public void delByUuids(Object[] uuids) throws DBException, ServiceException {
		sysUserDao.delBatch(SysUser.class, "uuid", uuids);
		sysUserRoleDao.delBatch(SysUserRole.class, "userId", uuids);
		sysUserDepGroupDao.delBatch(SysUserDepGroup.class, "userId",uuids);
		sysUserMenuDao.delBatch(SysUserMenu.class, "userId", uuids);
	}

	@Override
	public SysUser findByUuid(String uuid) throws DBException, ServiceException {
		return sysUserDao.get(SysUser.class, uuid);
	}

	@Override
	public Pager findByCondition(String cond, Pager pager)
			throws DBException, ServiceException {
		return  sysUserDao.findByCond(cond, pager);
	}

	@Override
	public SysUser findByUserName(String userName) throws DBException,
			ServiceException {
		return sysUserDao.findByUserName(userName);
	}
	
	  @Override
	  public void saveOrUpdateSysUserList(List<SysUserExcel> list) throws DBException, ServiceException {
	    SysUser user = (SysUser)SessionUtil.getAttribute("user");
	    for (SysUserExcel sysUserExcel : list) {
	      try {
	        SysUser m = null;

	        if(null==m){
	          m = new SysUser();
	        }
	        m.setTrueName(sysUserExcel.getTrueName());
	        m.setPosition(sysUserExcel.getPosition());
	        m.setMobile(sysUserExcel.getMobile());
	        m.setMail(sysUserExcel.getMail());
	        m.setQq(sysUserExcel.getQq());
	        if(!StringUtils.isEmpty(sysUserExcel.getDepGroup())){
	        	m.setDepGroup((SysDepGroup)sysUserDao.findUnique("from SysDepGroup where name=?",  new Object[]{sysUserExcel.getDepGroup()}));
//	          m.setMatCategory((Categories) customerDao.findUnique("from Categories where number=? ", new Object[]{materialExcel.getMatCategoryCode()}));
	        }
//	        if(!StringUtils.isEmpty(materialExcel.getBaseUnit())){
//	          m.setBaseUnit((BaseUnitMeasure) customerDao.findUnique("from BaseUnitMeasure where name=?", new Object[]{materialExcel.getBaseUnit()}));
//	        }
//	        if(!StringUtils.isEmpty(materialExcel.getExpiraDataUtil())){
//	          switch (materialExcel.getExpiraDataUtil()) {
//	            case "年":
//	              m.setExpiraDataUtil("year");
//	              break;
//	            case "季度":
//	              m.setExpiraDataUtil("quarter");
//	              break;
//	            case "月":
//	              m.setExpiraDataUtil("month");
//	              break;
//	            case "星期":
//	              m.setExpiraDataUtil("week");
//	              break;
//	            case "天":
//	              m.setExpiraDataUtil("day");
//	              break;
//	            case "小时":
//	              m.setExpiraDataUtil("hour");
//	              break;
//	            default:
//	              break;
//	          }
//	        }
//	        if(!StringUtils.isEmpty(materialExcel.getCreateUserName())){
//	          SysUser su = sysUserDao.findByUserName(materialExcel.getCreateUserName());
//	          m.setCreateUser(null==su?user:su);
//	        }
//	        if(!StringUtils.isEmpty(materialExcel.getUpdateUserName())){
//	          SysUser su = sysUserDao.findByUserName(materialExcel.getUpdateUserName());
//	          m.setAlterUser(null==su?user:su);
//	        }
	        
	        sysUserDao.saveOrUpdate(m);
	      } catch (Exception e) {
	    	  e.printStackTrace();
	      }
	     
	    }
	}
}
